package cn.wu.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.User;
import cn.wu.reggie.exception.BusinessException;
import cn.wu.reggie.mapper.UserMapper;
import cn.wu.reggie.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public R<User> login(String phone, String requestCode, String sessionCode) {

        //1.判断用户输入的验证码是否为空
        if (StrUtil.isBlank(requestCode)) {
            throw new BusinessException("验证码不能为空~");
        }

        //2.判断session中是否存在验证码
        if (StrUtil.isBlank(sessionCode)) {
            throw new BusinessException("请先获取验证码~");
        }

        //3.判断俩验证码是否一致
        if (!StrUtil.equals(requestCode, sessionCode)) {
            throw new BusinessException("请输入正确的验证码~");
        }

        //4.若一致,再通过手机号去数据库查询用户
        User user = getOne(new QueryWrapper<User>().eq("phone",phone));

        //5.若用户不存在,新增用户
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            save(user);
        }
        return R.success(null);
    }
}
